<!--学生管理-->
<template>
  <div class="log">
    <basic-container>
      <avue-crud
          ref="crud"
          class="top"
          :data="tableData"
          :option="tableOption"
          :page.sync="page"
          :permission="permissionList"
          :table-loading="tableLoading"
          @search-reset="searchReset"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @selection-change="selectionChange"
          @row-del="handleDel">
        <template slot="grouplist" slot-scope="scope">
              <el-tag
                  v-for="(grouplist,index) in scope.row.group"
                  :key="index">
                {{ grouplist.groupName }}
              </el-tag>
          <span v-if="scope.row.group === null">未设置</span>
        </template>
        <template slot="property" slot-scope="scope">
          <el-tag v-if="scope.row.property == '0'" type="success">{{ scope.label }}</el-tag>
          <el-tag v-else type="danger">{{ scope.label }}</el-tag>
        </template>
        <template slot="identityId" slot-scope="scope">
          <p style="margin: 0" v-if="scope.row.eye === false && scope.row.identityId !== null">{{scope.row.identityId}}
            <i class="icon-huabanfuben" style="margin:0 0 0 5px;font-size: 15px!important;" @click="showId(scope)"/>
          </p>
          <p style="margin: 0" v-if="scope.row.eye === true && scope.row.identityId !== null">{{scope.row.identityId1}}
            <i class="icon-yanjing1" style="margin:0 0 0 5px;font-size: 14px!important;" @click="showId(scope)"/>
          </p>
          <p style="margin: 0" v-if="scope.row.identityId == null">无</p>
        </template>
        <!--        <template slot="photoId" slot-scope="scope">-->
        <!--          <el-button v-if="scope.row.photoId !== null" label="small" type="warning" @click="showPhoto(scope.row)">查看大图-->
        <!--          </el-button>-->
        <!--          <p v-else>暂无数据</p>-->
        <!--        </template>-->
        <template slot="menu" slot-scope="scope">
          <el-button
              class="filter-item"
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handleEditItem(scope.row)">编辑
          </el-button>
          <el-button
              class="filter-item"
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDel(scope.row)">删除
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button
              class="filter-item"
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="handleItem()">新增
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button
              class="filter-item"
              icon="el-icon-upload2"
              size="small"
              type="success"
              @click="importItemVisible">导入
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button
              class="filter-item"
              icon="el-icon-download"
              size="small"
              type="warning"
              @click="exportItemVisible()">导出
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button
              class="filter-item"
              icon="el-icon-delete"
              size="small"
              type="danger"
              @click="batchDelVisible()">批量删除
          </el-button>
        </template>
      </avue-crud>
      <!--导入弹窗-->
      <el-dialog
          :visible.sync="setItemVisible"
          title="导入"
          center
          style="position: absolute"
          :close-on-click-modal="false"
          width="40%" @close="dictImportVisible">
        <el-form :model="form">
          <div class="upload-border" style="text-align: center">
            <el-form-item>
              <el-upload
                  ref="upload"
                  :auto-upload="false"
                  :before-upload="beforeUploadFile"
                  :file-list="fileList"
                  :http-request="handleupload"
                  :limit=limitNum
                  :on-change="handleChange"
                  :on-exceed="exceedFile"
                  accept=".xlsx"
                  action=""
                  drag>
                <!--                <el-button slot="trigger" style="margin-left: 0" type="success">导入文件</el-button>-->
                <i class="icon-yun-shangchuan"
                   style="font-size: 67px!important;color:#409EFF;position: relative;top:50px"></i>
                <div class="el-upload__text" style="position: relative;top:50px">点击此区域选择文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item style="text-align: center;margin-bottom: 0">
              <el-button @click="uploadItemVisible()">上传文件</el-button>
            </el-form-item>
            <el-form-item>
              <h4 style="display: inline-block;margin: 5px 0">
                提示：导入文件必须为Excel格式，您可以先
              </h4>
              <el-button
                  class="filter-item"
                  icon="el-icon-download"
                  size="small"
                  style="font-size: 15px;"
                  type="text"
                  @click="exportTempVisible">下载学生信息模板
              </el-button>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer">
        </div>
      </el-dialog>
      <!--人员新增-->
      <el-dialog
          :visible.sync="dialogAddVisible"
          title="新增"
          width="50%"
          :close-on-click-modal="false"
          center @close="dictItemVisible">
        <el-form>
          <el-form-item style="display: inline-block;float:left;width: 31%">
            <p></p>
            <el-upload
                ref="upload"
                :auto-upload="true"
                :headers="headers"
                v-loading="loading"
                element-loading-text="上传中"
                :before-upload="beforeUpload"
                :on-success="handleAvatarSuccess"
                :show-file-list="false"
                accept="image/png,image/gif,image/jpg,image/jpeg"
                action="/campus/persons/photo"
                class="avatar-uploader">
              <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
<!--            <el-button size="small" style="margin-left: 28%" type="primary" @click="uploadFile">立即上传</el-button>-->
          </el-form-item>
          <avue-form v-model="addform" :data="addData" :option="addOption" style="display: inline-block;width: 69%"></avue-form>
        </el-form>
        <div slot="footer">
          <el-button type="default" @click="dictItemVisible">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </div>
      </el-dialog>

      <!--图片查看-->
<!--      <el-dialog :visible.sync="imgsVisible" title="图片查看" width="20%">-->
<!--        <div style="  display: flex;justify-content: center;">-->
<!--          <el-image :src="avatarUrl" fit="scale-down" lazy style="margin: 20px auto;">-->
<!--            <div slot="error" class="image-slot">-->
<!--              <i class="el-icon-picture-outline"></i>-->
<!--            </div>-->
<!--          </el-image>-->
<!--        </div>-->
<!--        <div style=" display: flex;justify-content: center;">-->
<!--          <el-button style="width: 6vw; " type="primary" @click="imgsVisible = false">确 定</el-button>-->
<!--        </div>-->
<!--      </el-dialog>-->

      <!--人员编辑-->
      <el-dialog
          :visible.sync="dialogEditVisible"
          title="编辑"
          width="50%"
          :close-on-click-modal="false"
          center @close="dictItemEditVisible">
        <el-form>
          <el-form-item style="display: inline-block;float:left;width: 31%;">
            <el-upload
                ref="upload"
                :auto-upload="true"
                :headers="headers"
                v-loading="loading"
                element-loading-text="上传中"
                :before-upload="beforeUpload"
                :on-success="handleAvatarSuccess"
                :show-file-list="false"
                accept="image/png,image/gif,image/jpg,image/jpeg"
                action="/campus/persons/photo"
                class="avatar-uploader">
              <img v-if="avatarUrl" id="avatar" :src="avatarUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
<!--            <el-button size="small" style="margin-left: 28%" type="primary" @click="uploadFile">立即上传</el-button>-->
          </el-form-item>
          <avue-form v-model="editform" :data="editData" :option="editOption" style="display: inline-block;width: 69%"></avue-form>
        </el-form>
        <div slot="footer">
          <el-button type="default" @click="dictItemEditVisible">取消</el-button>
          <el-button type="primary" @click="handleEditSave">确定</el-button>
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {addStudent, delIdsObj, delStudent, editStudent, studentList} from '@/api/people/student'
import {addOption, editOption} from '@/const/crud/people/student'
import {mapGetters} from 'vuex'
import store from "@/store";
import {compressAccurately} from "image-conversion"
import {PERSON_DETAILS, PERSON_OPERA, STUDENT_PROPERTY, STUDENT_SEX,PERSON_IDS} from "@/const/personDict";
import {addScheduleObj} from "@/api/pass/s-newtimegroup";
import {getStore} from "@/util/store";
// import {VueCropper} from 'vue-cropper';

export default {
  name: 'Student',
  components: {
    // VueCropper,
  },
  data() {
    return {
      identityId:'',  //已打码身份证
      identityId1:'', //未打码身份证
      tableData: [],
      group: [],
      searchForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableLoading: false,
      addOption: addOption,
      editOption: editOption,
      dialogAddVisible: false,
      dialogEditVisible: false,
      setItemVisible: false,
      addData: [],
      editData: [],
      chooseList: [],
      addform: {},
      editform: {},
      avatarUrl: "",
      imgQuality: 0.9,  //图片压缩质量 imgQuality值越小，所绘制出的图像越模糊
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
        "TENANT-ID": getStore({ name: "tenantId" }),
      },
      // imgsVisible: false,
      limitNum: 1,
      fileList: [],
      form: {},
      loading: false,
      tableOption: {
        border: true,
        index: true,
        indexLabel: '序号',
        stripe: true,
        menuAlign: 'center',
        menuWidth: 180,
        menuType: 'button',
        align: 'center',
        refreshBtn: true,
        showClomnuBtn: false,
        searchSize: 'mini',
        searchMenuSpan: 6,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        selection: true,
        reserveSelection: true,
        searchLabelWidth: 86,
        props: {
          label: 'label',
          value: 'value'
        },
        column: [{
          label: '人员id',
          prop: 'id',
          hide: true,
          viewDisplay: false,
          editDisplay: false,
        }, {
          label: '姓名',
          prop: 'personName',
          type: 'input',
          search: true,
        }, {
          label: '学号',
          prop: 'number',
          dicData: PERSON_DETAILS,
        }, {
          label: '性别',
          prop: 'sex',
          search: true,
          type: 'select',
          dicData: STUDENT_SEX,
          change: (value) => {
            this.searchForm.sex = value.value
            this.getList(this.page, this.searchForm)
          },
        },  {
          label: '校区',
          prop: 'campusDeptArea',
          dicData: PERSON_DETAILS,
          editDisplay: false,
        },{
          label: '年级',
          prop: 'parentName',
          type: 'select',
          dicData: PERSON_DETAILS,
          editDisplay: false,
        },
          {
            label: '年级',
            prop: 'deptId',
            search: true,
            type: 'select',
            hide: true,
            defaultExpandAll: true,
            dicUrl: '/admin/dept/PermissionTree',
            cascaderItem: ['deptName'],
            dicFormatter: (res) => {
              let gradeArr = res.data
              let value = []
              if(gradeArr.length> 0){
                for(let i of gradeArr){
                  if(i.typeNum == "2" && i.isLock === false){
                    value.push(i)
                  }
                }
                console.log(value)
                return value
              }
              // let gradeArr= res.data[0].children[0].children
              // let value=[]
              // if(gradeArr.length > 1){
              //   for(let i of gradeArr){
              //     if(i.children.length>0){
              //       for(let j of i.children){
              //         value.push(j)
              //       }
              //     }
              //   }
              //   return value
              // }else{
              //   return gradeArr[0].children;
              // }
            },
            dicMethod: 'get',
            props: {
              label: 'name',
              value: 'id'
            },
            change: (value) => {
              this.searchForm.deptId = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          {
            label: '班级',
            prop: 'deptName',
            search: true,
            filter: false,
            type: 'select',
            defaultExpandAll: true,
            dicUrl: '/campus/sysdept/detpTree/{{key}}/1,2,3',
            dicFormatter: (res) => {
              return res.data[0].children;//返回字典的层级结构
            },
            dicMethod: 'get',
            props: {
              label: 'name',
              value: 'deptId',
            },
            change: (value) => {
              this.searchForm.deptId = value.value
              this.getList(this.page, this.searchForm)
            },
          }, {
          label: '学生属性',
          prop: 'identityKey',
          search: true,
          type: 'select',
          dicUrl: '/campus/identity/selectAll?groupNum=2',
          dicMethod: 'get',
          props: {
            label: 'name',
            value: 'id'
          },
          change: (value) => {
            this.searchForm.identityKey = value.value
            this.getList(this.page, this.searchForm)
          },
        },
          {
            label: '身份证号',
            prop: 'identityId',
            dicData: PERSON_DETAILS,
            width: 165,
            slot: true, //加隐藏显示身份证号
          },
          {
          label: '楼栋',
          prop: 'buildingName',
          dicData: PERSON_DETAILS,
        }, {
          label: '楼栋',
          prop: 'buildingId',
          hide: true,
          search: true,
          type: 'select',
          dicUrl: '/campus/building/selectAll',
          dicMethod: 'get',
          props: {
            label: 'buildingName',
            value: 'buildingId'
          },
          change: (value) => {
            this.searchForm.buildingId = value.value
            this.getList(this.page, this.searchForm)
          },
        },
          {
            label: '宿舍号',
            prop: 'dormNumber',
            dicData: PERSON_DETAILS,
            search: true,
            type: 'input',
          }, {
            label: '手机号',
            prop: 'phone',
            hide: true,
            viewDisplay: true,
          }, {
            width: 100,
            label: '人脸照片',
            prop: 'photoId',
            type: 'upload',
            listType: 'picture-img',
            propsHttp: {
              home: '/campus/persons/photo/'
            },
          },
          // {
          //   width: 120,
          //   label: '可通行门禁',
          //   prop: 'grouplist',
          //   slot: true,
          // }, {
          //   width: 130,
          //   label: '通行方案',
          //   prop: 'schemeName',
          //   type: 'select',
          //   dicData: PERSON_DETAILS
          // },
          {
            width: 120,
            label: '人员修改时间',
            prop: 'updateTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            editDisplay: false,
          }, {
            width: 100,
            label: '修改操作人',
            prop: 'operator',
            editDisplay: false,
            dicData: PERSON_OPERA
          }, {
            label: '状态',
            prop: 'property',
            search: true,
            slot: true,
            type: 'select',
            addDisplay: false,
            dicData: STUDENT_PROPERTY,
            change: (value) => {
              this.searchForm.property = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          {
            label: '有无身份证',
            prop: 'identityIdIsNull',
            dicData: PERSON_IDS,
            hide:true,
            search: true,
            type: 'select',
            slot: true,
            change: (value) => {
              this.searchForm.identityIdIsNull = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          // {
          //   label: '年级/班级',
          //   prop: 'deptId',
          //   search: true,
          //   filter: false,
          //   type: 'tree',
          //   hide: true,
          //   dicUrl: '/campus/sysdept/detpTree/1/2,3',
          //   dicMethod: 'get',
          //   // dicData: [],
          //   props: {
          //     label: 'name',
          //     value: 'deptId',
          //   },
          //   change: (value) => {
          //     if(value.value === ''){
          //       return;
          //     }
          //     this.searchForm.deptId = value.value
          //     this.getList(this.page, this.searchForm)
          //   },
          // },
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permissions.sys_log_del, true)
      }
    },
  },
  created() {
    // this.initData()
  },
  methods: {
    //显隐手机号
    showId(scope){
      if(scope.row.eye === false){
        scope.row.eye = true //显示未打码的身份证，小眼睛睁开
      }else if(scope.row.eye === true){
        scope.row.eye = false  //显示已打码身份证，小眼睛关闭
      }
    },

    //展示表格
    getList(page, params, row) {
      this.tableLoading = true
      studentList(Object.assign({
        descs: 'create_time',
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        for(var i=0; i<response.data.data.records.length; i++) {
          let identityId = response.data.data.records[i].identityId
          if (identityId !== null) {
            let newIdentityId = identityId.replace(/^(.{6})(?:\d+)(.{4})$/,"\$1********\$2");  //手机号打码正则
            response.data.data.records[i].identityId = newIdentityId  //已打码
            response.data.data.records[i].identityId1 = identityId  //未打码
            }
          }
        this.tableData.map(item => {
          this.$set(item, 'eye')
          item.eye = false
        })
        this.page.total = response.data.data.total
        this.tableLoading = false
      })
    },

    //新增提交
    handleSave: function (row) {
      this.addform.photoId = this.photoId
      if (this.addform.personName == null || this.addform.personName == '') {
        this.$message.error("请输入姓名")
        return
      }else {
        this.addform.personName = this.addform.personName.trim()
      }
      if (this.addform.dept == null) {
        this.$message.error("请选择所在年级")
        return
      }
      if (this.addform.deptName == '') {
        this.$message.error("请选择所在班级")
        return
      }
      if (this.addform.identityKey == null){
        this.$message.error("请选择学生属性")
        return
      }
      if (this.addform.identityId == null){
        this.$message.error("请输入身份证号")
        return
      }
      let Id = /(^\d{17}(\d|X|x)$)/
      if (!Id.test(this.addform.identityId)){
        this.$message.error("请输入正确的身份证号")
        return
      }
      if (this.addform.sex == null){
        this.$message.error("请选择性别")
        return
      }
      if (this.addform.identityKey !== 40){
        if (this.addform.buildingId == null){
          this.$message.error("请选择楼栋")
          return
        }
        if (this.addform.dormNumber == null){
          this.$message.error("请输入宿舍号")
          return
        }
      }
      let acount = /^[1][0-9][0-9]{9}$/
      if (this.addform.phone.length !== 11 ||!acount.test(this.addform.phone)){
        this.$message.error("请输入正确手机号")
        return
      }
      let loading = this.$loading({
        lock: true,
        text: '添加中，请稍等',
      })
      this.addform.deptId = this.addform.deptName
      addStudent(this.addform).then(res => {
        if (res.data.code === 0) {
          if (this.addform.identityKey === 40) {
            let param = {
              personId: res.data.data,
              timePlanId: 230,
              timeType: 0
            }
            addScheduleObj(param).then(res => {
              if (res.data.code === 0) {
                this.$message.success('添加成功')
              } else {
                this.$message.error('人员添加成功，时间方案分配失败')
              }
            })
          } else {
            let param = {
              personId: res.data.data,
              timePlanId: 219,
              timeType: 0
            }
            addScheduleObj(param).then(res => {
              if (res.data.code === 0) {
                this.$message.success('添加成功')
              } else {
                this.$message.error('人员添加成功，时间方案分配失败')
              }
            })
          }
        } else {
          this.$message.error('添加失败')
        }
        // for (let key of Object.keys(this.addform)) {
        //   Vue.delete(this.addform, key);
        // }
        this.addform.personName = null
        this.addform.number = null
        this.addform.pid = null
        this.addform.dept = null
        this.addform.identityKey = null
        this.addform.identityId = null
        this.addform.sex = null
        this.addform.schemeId = null
        this.addform.buildingId = null
        this.addform.dormNumber = null
        this.addform.phone = null
        this.dialogAddVisible = false
        loading.close()
        // done()
        this.getList(this.page)
        this.addform = {}
        console.log(row)
      })
        .catch(err => {
            loading.close()
            this.$message.error("添加失败");
        });
    },

    //  处理级联的树状数据
    // initData() {
    //   // debugger
    //   let arr = []
    //   let column = this.findObject(this.tableOption.column, "deptId");
    //   deptList(0, -1, {}).then(res => {
    //     arr = res.data.data.map((item) => {
    //       return Object.assign({}, {'name': item.name, 'deptId': item.deptId, 'children': item.children})
    //     })
    //     console.log(arr)
    //     column.dicData = []
    //     column.dicData = arr[0].children;
    //     let data = column.dicData
    //     this.options = this.deptIdList(data)
    //   })
    // },
    // deptIdList(data) {
    //   // debugger
    //   data.forEach(items => {
    //     if (items.children.length > 0) {
    //       this.deptIdList(items.children);
    //     } else {
    //       items.children = undefined;
    //     }
    //   })
    // },

    //新增编辑弹窗上传图片
    handleAvatarSuccess(res, file, fileList) {
      this.loading = true
      if (res.code === 0) {
        this.avatarUrl = URL.createObjectURL(file.raw);
        this.photoId = res.data;
        this.$message.success('上传成功')
        this.loading = false
        console.log(file)
      } else if (res.code === 1) {
        this.$message.error(res.msg)
        this.loading = false
      }
    },

    //立即上传
    // uploadFile() {
    //   this.loading = true
    //   this.$refs.upload.submit()
    // },

    //图片压缩
    beforeUpload (file) {
      this.loading = true
      console.log('压缩前', file)
      const _this = this
      return new Promise(resolve => {
        const reader = new FileReader()
        const image = new Image()
        image.onload = (imageEvent) => {
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          const width = image.width * _this.imgQuality
          const height = image.height * _this.imgQuality
          canvas.width = width;
          canvas.height = height;
          context.clearRect(0, 0, width, height);
          context.drawImage(image, 0, 0, width, height);
          const avatarUrl = canvas.toDataURL(file.type);
          const blobData = _this.dataURItoBlob(avatarUrl, file.type);
          resolve(blobData)
        }
        // 压缩到100KB,这里的100就是要压缩的大小,可自定义
        compressAccurately(file,1024).then(res => {
          res = new File([res], file.name, {type: res.type,lastModified: Date.now()})
          resolve(res)
          console.log('压缩后', res);
        })
      })
    },
    dataURItoBlob(dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type: type});
    },

    //批量上传
    importItemVisible() {
      this.setItemVisible = true
    },

    //导入
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });
    },

    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      console.log('change')
      console.log(file)
      this.form.file = file.raw
      console.log(this.form.file)
      console.log(fileList)
    },

    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      console.log('before upload')
      console.log(file)
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      let size = file.size / 1024 / 1024
      if (extension !== 'xlsx') {
        this.$notify.warning({
          title: '警告',
          message: `只能上传Excel2017（即后缀是.xlsx）的文件`
        });
      }
      if (size > 10) {
        this.$notify.warning({
          title: '警告',
          message: `文件大小不得超过10M`
        });
      }
    },

    //文件上传执行
    handleupload() {
      const data = new FormData()
      const fileUps = this.form.file
      data.append('file', fileUps)
      let loading = this.$loading({
        lock: true,
        text: '上传中，请稍等'
      })
      this.$axios({
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        url: '/campus/student/excel_Import',
        data: data,
        method: 'post',
        timeout: 600000,
      }).then(res => {
        if (res.data === "success") {
          loading.close()
          this.$message.success('文件上传成功')
          console.log(this.$message)
        } else {
          loading.close()
          this.$message.error('文件上传失败')
        }
        this.$refs['upload'].clearFiles();
        this.setItemVisible = false
        loading.close()
        this.getList(this.page)
      })
       .catch(err => {
         loading.close()
         this.$message.error("文件上传失败");
       });
    },

    //上传文件提交
    uploadItemVisible() {
      if (this.$refs.upload.uploadFiles.length < 1) {
        this.$message.warning('请选择上传文件')
      } else {
        this.$refs.upload.submit()
      }
    },

    //关闭导入弹窗
    dictImportVisible() {
      this.setItemVisible = false
      this.$refs['upload'].clearFiles();
    },

    //导出文件
    exportItemVisible() {
      const h = this.$createElement
      this.$confirm('确定要导出当前筛选条件下的学生吗?', '导出学生信息', {
        message: h('p', null, [
          h('h3', {style: 'font-weight:bold;'}, '确定要导出当前筛选条件下的学生吗?'),
          h('p', {style: 'color:red'}, '导出文件需要较长时间，请耐心等待'),
        ]),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal:false,
      }).then(() => {
        let loading = this.$loading({
          lock: true,
          text: '导出中，请稍等'
        })
        axios({
          method: 'get',
          url: '/campus/student/excel_export',
          params: this.searchForm,
          timeout: 600000,
          headers: {
            key: ''
          },
          responseType: "blob"
        }).then(res => {
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel"
            });
            let link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', '学生信息导出文件.xlsx');
            link.click();
            link = null;
            loading.close()
            this.$message.success('导出成功');
          } else {
            // 返回json
            this.$message.warning(res.data.msg);
          }
        })
            .catch(err => {
              loading.close()
              this.$message.error("导出失败");
            });
      })
    },

    //导入模板下载
    exportTempVisible() {
      axios({
        method: 'get',
        url: '/campus/student/excel_template',
        params: this.searchForm,
        headers: {
          key: ''
        },
        responseType: "blob"
      })
          .then(res => {
            if (res.data.type) {
              // 文件下载
              const blob = new Blob([res.data], {
                type: "application/vnd.ms-excel"
              });
              let link = document.createElement('a');
              link.href = URL.createObjectURL(blob);
              link.setAttribute('download', '导入学生信息模板.xlsx');
              link.click();
              link = null;
              this.$message.success('下载成功');
            } else {
              // 返回json
              this.$message.warning(res.data.msg);
            }
          })
          .catch(err => {
            this.$message.error("下载失败");
          });
    },

    //查看大图
    // showPhoto(row) {
    //   this.imgsVisible = true
    //   axios({
    //     method: 'get',
    //     url: '/campus/persons/photo/' + row.photoId,
    //     headers: {
    //       "Content-Type": "application/json",
    //     },
    //     responseType: 'arraybuffer',
    //   }).then(res => {
    //     this.avatarUrl = "data:image/png;base64," + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
    //     // console.log(this.avatarUrl)
    //   }).catch(e => {
    //     throw e;
    //   })
    // },

    //删除
    handleDel: function (row) {
      this.$confirm('是否确认删除"' + row.personName + '"?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal:false,
      }).then(function () {
        return delStudent(row.id)
      }).then(() => {
        this.getList(this.page)
        this.$message.success('删除成功')
      })
    },

    // 表格的多选方法
    selectionChange(list) {
      // this.$message.success('选中的数据'+ JSON.stringify(list));
      this.chooseList = list
    },

    //新增弹窗相关
    handleItem: function () {
      // for (let key of Object.keys(this.addform)) {
      //   Vue.delete(this.addform, key);
      // }
      this.addform.personName = null
      this.addform.deptId = null
      this.addform.deptName = null
      this.addform.number = null
      this.addform.identityKey = null
      this.addform.identityId = null
      this.addform.sex = null
      this.addform.schemeId = null
      this.addform.buildingId = null
      this.addform.dormNumber = null
      this.addform.phone = null
      this.dialogAddVisible = true
      this.avatarUrl = null
    },

    //新增弹窗关闭
    dictItemVisible: function () {
      // this.$refs['upload'].clearFiles();
      this.avatarUrl = null
      this.photoId = null
      this.addform.personName = null
      this.addform.dept = null
      this.addform.deptName = null
      this.addform.number = null
      this.addform.identityKey = null
      this.addform.identityId = null
      this.addform.sex = null
      this.addform.schemeId = null
      this.addform.buildingId = null
      this.addform.dormNumber = null
      this.addform.phone = null
      this.dialogAddVisible = false
      // if(this.avatarUrl == null){
      //
      // }else{
      // for (let key of Object.keys(this.addform)) {
      //   Vue.delete(this.addform, key);
      // }
      // if(this.photoId !== ''){
      //  delStudentPhoto(this.photoId)
      // }
      // }
    },

    //编辑弹窗相关
    handleEditItem: function (row) {
      this.dialogEditVisible = true
      // let param = {
      //   id: row.id
      // }
      // // debugger
      // studentList(param).then(res => {
      //   this.editform = res.data.data.records[0]
      //   console.log(thigs.editform)
      // })
      console.log(row)
      this.curApiList = JSON.parse(JSON.stringify(row));
      this.editform = this.curApiList;
      // this.editform.pid = row.pid
      // 获取门禁组
      // if (row.group !== null) {
      //   this.editform.accessControlIds = row.group.map(x => {
      //     return x.id
      //   })
      // }
      this.avatarUrl = null
      axios({
        method: 'get',
        url: '/campus/persons/photo/' + this.editform.photoId,
        headers: {
          "Content-Type": "application/json",
          "TENANT-ID": getStore({ name: "tenantId" })
        },
        responseType: 'arraybuffer',
      }).then(res => {
        this.avatarUrl = "data:image/png;base64," + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
      }).catch(e => {
        this.$message.error("图片上传失败");
      })
    },

    //编辑提交
    handleEditSave: function () {
       if (this.editform.personName == null || this.editform.personName == ''){
        this.$message.error("请输入姓名")
        return
      }else {
         this.editform.personName = this.editform.personName.trim()
       }
      if (this.editform.deptId == null){
        this.$message.error("请选择所在年级")
        return
      }
      if (this.editform.deptName == ''){
        this.$message.error("请选择所在班级")
        return
      }
      if (this.editform.identityKey == null){
        this.$message.error("请选择学生属性")
        return
      }
      if (this.editform.identityId1 == null){
        this.$message.error("请输入身份证号")
        return
      }
      let Id = /(^\d{17}(\d|X|x)$)/
      if (!Id.test(this.editform.identityId1)){
        this.$message.error("请输入正确的身份证号")
        return
      }
      if (this.editform.sex == null){
        this.$message.error("请选择性别")
        return
      }
      if (this.editform.identityKey !== 40){
        if (this.editform.buildingId == null){
          this.$message.error("请选择楼栋")
          return
        }
        if (this.editform.dormNumber == null){
          this.$message.error("请输入宿舍号")
          return
        }
      }
      if (this.editform.phone.length !== 11){
        this.$message.error("请输入正确手机号")
        return
      }
      let loading = this.$loading({
        lock: true,
        text: '修改中，请稍等'
      })
      this.editform.photoId = this.photoId
      this.editform.identityId = this.editform.identityId1
      if (this.editform.identityKey === 40){
        this.editform.buildingId = null
        this.editform.dormNumber = null
      }
      editStudent(this.editform).then(res => {
        if (res.data.code === 0) {
          this.$message.success('修改成功')
        } else {
          this.$message.error('修改失败')
        }
        this.dialogEditVisible = false
        loading.close()
        this.getList(this.page)
        // for (let key of Object.keys(this.editform)) {
        //   Vue.delete(this.editform, key);
        // }
      })
        .catch(err => {
            loading.close()
            this.$message.error("修改失败");
        });
    },

    //编辑弹窗关闭
    dictItemEditVisible: function () {
      this.dialogEditVisible = false
      // for (let key of Object.keys(this.editform)) {
      //   Vue.delete(this.editform, key);
      // }
     this.editform = this.curApiList;
      this.avatarUrl = null
      this.photoId = null
      this.editform.personName = null
      this.editform.deptId = null
      this.editform.deptName = null
      this.editform.number = null
      this.editform.identityKey = null
      this.editform.identityId = null
      this.editform.identityId1 = null
      this.editform.sex = null
      this.editform.schemeId = null
      this.editform.buildingId = null
      this.editform.dormNumber = null
      this.editform.phone = null
    },

    //批量删除
    batchDelVisible: function () {
      let ids = this.chooseList.map(x => {
        return x.id
      })
      console.log(ids)
      if (ids.length === 0) {
        this.$message.error('请选择要批量删除的人员')
      } else {
        this.$confirm('是否确认删除所选人员?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal:false,
        }).then(function () {
          return delIdsObj(ids)
        }).then(res => {
          if (res.data.code === 0) {
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除失败')
          }
          this.dialogbetchDelVisible = false
          this.getList(this.page)
        })
      }
    },

    //搜索页面内容
    searchChange(form, done) {
      if (form.deptName !== undefined) {
        form.deptId = form.deptName
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      }
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },

    //点击每页多少条会调size-change方法回调
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },

    //点击页码会调用current-change方法回调当前页
    currentChange(current) {
      this.page.currentPage = current
    },
    refreshChange() {
      this.getList(this.page)
    },

    //清空时重置页面
    searchReset() {
      this.searchForm = {};
      this.getList(this.page)
    },
  }
}
</script>
<style scoped>
.cropper-content{
  width:500px;height:500px;background: pink;
}
.cropper{
  width:500px;
  height:500px;
  background: yellow;
}
</style>
<style>
.el-carousel__item,.el-carousel__mask{
  left:40% !important;
}
</style>
<style scoped>
/deep/ .top .el-form-item__label {
  text-align: left;
}

/deep/ .top .avue-form__row {
  padding-left: 4px !important;
  padding-right: 36px !important;
}

/deep/ .avue-form__menu--center {
  text-align: left;
}

.upload-border {
  width: 70%;
  height: 280px;
  margin: 0 auto;
  /*border: dashed 3px  #409EFF;*/
}

/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 0;
}

/deep/ .el-upload-list__item-name {
  margin: 0 0 10px 0;
  padding-left: 0;
}

/deep/ .el-upload-list__item:first-child {
  margin: 0;
}

/deep/ .el-upload-dragger {
  width: 420px;
}
</style>
